import { makeAutoObservable, action } from 'mobx';

class SoundStore {
  // 默认开启声音
  isSoundEnabled: boolean = true;
  // 默认音量为100%
  volume: number = 100;

  constructor() {
    makeAutoObservable(this);
    // 尝试从localStorage加载声音设置
    this.loadSoundSettings();
  }

  // 从localStorage加载声音设置
  @action
  loadSoundSettings(): void {
    const savedSoundEnabled = localStorage.getItem('soundEnabled');
    const savedVolume = localStorage.getItem('soundVolume');
    
    if (savedSoundEnabled !== null) {
      this.isSoundEnabled = savedSoundEnabled === 'true';
    }
    
    if (savedVolume !== null) {
      const volume = parseInt(savedVolume, 10);
      if (!isNaN(volume) && volume >= 0 && volume <= 100) {
        this.volume = volume;
      }
    }
  }

  // 切换声音开关
  @action
  toggleSound(): void {
    this.isSoundEnabled = !this.isSoundEnabled;
    // 保存到localStorage
    localStorage.setItem('soundEnabled', this.isSoundEnabled.toString());
  }

  // 设置声音开关状态
  @action
  setSoundEnabled(enabled: boolean): void {
    this.isSoundEnabled = enabled;
    localStorage.setItem('soundEnabled', enabled.toString());
  }

  // 设置音量
  @action
  setVolume(volume: number): void {
    // 确保音量在0-100之间
    this.volume = Math.max(0, Math.min(100, volume));
    // 保存到localStorage
    localStorage.setItem('soundVolume', this.volume.toString());
  }

  // 获取音量的实际值（0-1之间）
  getVolumeLevel(): number {
    return this.volume / 100;
  }

  // 检查声音是否可以播放
  canPlaySound(): boolean {
    return this.isSoundEnabled && this.volume > 0;
  }
}

export default SoundStore;